﻿using FDSQLAssistant.Extensions;
using FDSQLAssistant.Models;
using System;
using System.Linq;

namespace FDSQLAssistant.Repositories
{
    public class MySqlCommonRepository : ContextRepository, ICommonRepository
    {
        public DbType DbType() => Models.DbType.MySql;

        public TableInfo GetTableInfo(string tableName)
        {
            var database = _config.ConnectionString.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(x =>
            {
                var str = x.Trim();
                return x.IndexOf("database", StringComparison.OrdinalIgnoreCase) == 0 || x.IndexOf("initial catalog", StringComparison.OrdinalIgnoreCase) == 0;
            });
            if (database.IsNullOrEmpty())
            {
                throw new Exception($"{tableName}数据库连接有误");
            }

            database = database.Split(new[] { '=' }).Last();
            if (database.IsNullOrEmpty())
            {
                throw new Exception($"{tableName}数据库连接有误{database}");
            }
            var sql =
                @"SELECT COLUMN_NAME `name`,DATA_TYPE type,character_maximum_length length,
	CASE WHEN EXTRA='auto_increment' THEN 1 ELSE 0 END isIdentity,
						CASE WHEN column_key='PRI' THEN 1 ELSE 0 END `key` FROM information_schema.COLUMNS WHERE table_schema=@database
						AND table_name=@tableName;";
            var columns = Query<ColumnInfo>(sql, new { database, tableName });
            return new TableInfo
            {
                Name = tableName,
                ColumnInfos = columns
            };
        }

        public MySqlCommonRepository(Config config) : base(config)
        {
        }
    }
}
